package com.chris.homecare.screens
{
	import com.chris.homecare.components.BreadcrumbComponenet;
	import com.chris.homecare.components.BulletHeadingComp;
	import com.chris.homecare.components.HeaderComponent;
	import com.chris.homecare.components.StarRatting;
	import com.chris.homecare.components.TextAreaComponent;
	import com.chris.homecare.data.FetchRemoteData;
	import com.chris.homecare.utils.CommonUtils;
	import com.chris.homecare.utils.ScreenNames;
	import com.chris.homecare.utils.ShowNativeAlert;
	
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.filesystem.File;
	import flash.net.URLLoader;
	import flash.net.URLRequest;
	import flash.net.URLRequestMethod;
	
	import feathers.controls.Button;
	import feathers.controls.ImageLoader;
	import feathers.controls.Label;
	import feathers.controls.LayoutGroup;
	import feathers.controls.Screen;
	import feathers.controls.ScrollContainer;
	import feathers.controls.TextInput;
	import feathers.events.FeathersEventType;
	import feathers.layout.HorizontalLayout;
	import feathers.layout.VerticalLayout;
	
	import pl.mateuszmackowiak.nativeANE.events.NativeDialogEvent;
	
	import starling.display.Quad;
	import starling.events.Event;
	
	[Event(name="triggerCustomerReview",type="starling.events.Event")]
	public class WriteReviewScreen extends Screen
	{
		public static const TRIGGER_CUSTOMER_REVIEW:String = "triggerCustomerReview";
		
		private var bulletHeadingComp:BulletHeadingComp;
		private var headerComp:HeaderComponent;
		private var breadcrumbComp:BreadcrumbComponenet;
		private var ratingLayoutGroup:LayoutGroup;

		private var nameLabel:Label;
		private var titleLabel:Label;
		private var bottomRule:Quad;
		private var ratingTxtComp:TextAreaComponent;

		private var contentLayoutGroup:LayoutGroup;

		private var nameTextInput:TextInput;

		private var commentsErrorLabel:Label;

		private var nameLabel2:Label;
		private var nameCityLabel:Label;

		private var nameErrorLabel:Label;

		private var ratingComp:StarRatting;

		private var scroller:ScrollContainer;

		private var submitBtnLayoutGroup:LayoutGroup;
		
		private var isKeyBoardActiveForTextArea:Boolean = false;
		private var fullScrollerHeight:Number;

		public function WriteReviewScreen()
		{
			super();
		}
		
		override protected function initialize():void
		{
			this.layout = new VerticalLayout();
			
			CommonUtils.previousScreen = ScreenNames.REVIEW_SCREEN;
			headerComp = new HeaderComponent();
			headerComp.addEventListener(starling.events.Event.COMPLETE, onMenuBtnTrigger);
			addChild(headerComp);
			
			breadcrumbComp = new BreadcrumbComponenet("Info", "Team","Ratings & Review");
			addChild(breadcrumbComp);
			
			scroller = new ScrollContainer();
			scroller.layout = new VerticalLayout();
			addChild(scroller);
			
			bulletHeadingComp = new BulletHeadingComp("Write a Review");
			scroller.addChild(bulletHeadingComp);
			
			var employeeGroup:LayoutGroup = new LayoutGroup();
			var empLayout:HorizontalLayout = new HorizontalLayout();
			empLayout.verticalAlign = HorizontalLayout.VERTICAL_ALIGN_MIDDLE;
			empLayout.gap = 30;
			empLayout.paddingTop = empLayout.paddingBottom = 5*CommonUtils.scaleValue;
			empLayout.paddingLeft = 15*CommonUtils.scaleValue;
			employeeGroup.layout = empLayout;
			scroller.addChild(employeeGroup);
			
			var imageGroup:LayoutGroup = new LayoutGroup();
			imageGroup.clipContent = true;
			employeeGroup.addChild(imageGroup);
			var employeeImg:ImageLoader = new ImageLoader();
			employeeImg.width = 100*CommonUtils.scaleValue;
			employeeImg.source = File.applicationStorageDirectory.resolvePath(FetchRemoteData.choosenEmployeeData.imageUrl).url;
			imageGroup.addChild(employeeImg);
			
			var imageFrame:ImageLoader = new ImageLoader();
			imageFrame.source = "assets/images/homecare/image-overlay.png";
			imageFrame.width = 100*CommonUtils.scaleValue;
			employeeImg.layoutData = layoutData;
			imageFrame.layoutData = layoutData;
			imageGroup.addChild(imageFrame);
			imageGroup.width = imageGroup.height = 100*CommonUtils.scaleValue;
			
			var employeeLblGroup:LayoutGroup = new LayoutGroup();
			employeeLblGroup.layout = new VerticalLayout();
			employeeGroup.addChild(employeeLblGroup);
			
			nameLabel2 = new Label();
			nameLabel2.text = FetchRemoteData.choosenEmployeeData.name;
			nameLabel2.nameList.add("employee-name-label");
			employeeLblGroup.addChild(nameLabel2);
			
			titleLabel = new Label();
			titleLabel.text = FetchRemoteData.choosenEmployeeData.position;
			titleLabel.nameList.add("employee-title-label");
			employeeLblGroup.addChild(titleLabel);
			
			bottomRule = new Quad(10,1, 0xEEEEEE);
			scroller.addChild(bottomRule);
			
			var gappingQuad1:Quad = new Quad(10,10*CommonUtils.scaleValue, 0xFFFFFF);
			scroller.addChild(gappingQuad1);
			
			contentLayoutGroup = new LayoutGroup();
			var contentLayout:VerticalLayout = new VerticalLayout();
			contentLayout.paddingLeft = contentLayout.paddingRight = 20*CommonUtils.scaleValue;
			contentLayout.gap = 5*CommonUtils.scaleValue;
			contentLayoutGroup.layout = contentLayout;
			scroller.addChild(contentLayoutGroup);
			
			nameCityLabel = new Label();
			nameCityLabel.nameList.add("form-heading-lbl");
			nameCityLabel.text = "Name - City";
			contentLayoutGroup.addChild(nameCityLabel);
			
			nameTextInput = new TextInput();
			nameTextInput.nameList.add("custom-text-input");
			nameTextInput.prompt = "Please enter your name";
			nameTextInput.addEventListener(FeathersEventType.FOCUS_IN, onNameTextFocus);
			contentLayoutGroup.addChild(nameTextInput);
			
			nameErrorLabel = new Label();
			nameErrorLabel.visible = false;
			nameErrorLabel.text = "Name-City should not be empty";
			nameErrorLabel.nameList.add("error-label");
			contentLayoutGroup.addChild(nameErrorLabel);
			
			var gappingQuad2:Quad = new Quad(10,10*CommonUtils.scaleValue, 0xFFFFFF);
			contentLayoutGroup.addChild(gappingQuad2);
			
			var commentsLbl:Label = new Label();
			commentsLbl.text = "Comments";
			commentsLbl.x = commentsLbl.y = 10*CommonUtils.scaleValue;
			commentsLbl.nameList.add("form-heading-lbl");
			contentLayoutGroup.addChild(commentsLbl);
			
			ratingTxtComp = new TextAreaComponent();
			ratingTxtComp.x = 20*CommonUtils.scaleValue;
			ratingTxtComp.height = 250*CommonUtils.scaleValue;
			contentLayoutGroup.addChild(ratingTxtComp);
			ratingTxtComp.textArea.addEventListener(FeathersEventType.FOCUS_IN, onCommentTextFocus);
			
			commentsErrorLabel = new Label();
			commentsErrorLabel.text = "Comments should not be empty";
			commentsErrorLabel.visible = false;
			commentsErrorLabel.nameList.add("error-label");
			commentsErrorLabel.x = 20*CommonUtils.scaleValue;
			contentLayoutGroup.addChild(commentsErrorLabel);
			
			var gappingQuad3:Quad = new Quad(10,10*CommonUtils.scaleValue, 0xFFFFFF);
			contentLayoutGroup.addChild(gappingQuad3);
			
			var rateMeLbl:Label = new Label();
			rateMeLbl.text = "Rate Me";
			rateMeLbl.nameList.add("form-heading-lbl");
			contentLayoutGroup.addChild(rateMeLbl);
			
			ratingComp = new StarRatting();
			contentLayoutGroup.addChild(ratingComp);
			
			submitBtnLayoutGroup = new LayoutGroup();
			var submitBtnLayout:VerticalLayout = new VerticalLayout();
			submitBtnLayout.paddingTop = 20*CommonUtils.scaleValue;
			submitBtnLayout.horizontalAlign = VerticalLayout.HORIZONTAL_ALIGN_CENTER;
			submitBtnLayoutGroup.layout = submitBtnLayout;
			contentLayoutGroup.addChild(submitBtnLayoutGroup);
			
			var submitBtn:Button = new Button();
			submitBtn.nameList.add("performance-btn");
			submitBtn.label = "Submit";
			submitBtn.addEventListener(starling.events.Event.TRIGGERED, onFormSubmited);
			submitBtnLayoutGroup.addChild(submitBtn);
			
			super.initialize();
		}
		
		override protected function draw():void
		{
			bottomRule.width = this.width - 40*CommonUtils.scaleValue;
			submitBtnLayoutGroup.width = nameTextInput.width = ratingTxtComp.width = this.width - 40*CommonUtils.scaleValue;
			
			if(!isKeyBoardActiveForTextArea)
			{
				scroller.height = stage.stageHeight - (scroller.y + 40*CommonUtils.scaleValue);
				fullScrollerHeight= scroller.height;
			}
			else 
			{
				scroller.height = (fullScrollerHeight - ratingTxtComp.y);
				scroller.scrollToPosition(0,ratingTxtComp.y, 0);
			}
			
			super.draw();
		}
		
		private function onMenuBtnTrigger(event:starling.events.Event):void
		{
			
		}
		
		private function onFormSubmited():void
		{
			if((nameTextInput.text == "") || (ratingTxtComp.textArea.text == ""))
			{
				if(nameTextInput.text == "")
				{
					nameErrorLabel.visible = true;
				}
				
				if(ratingTxtComp.textArea.text == "")
				{
					commentsErrorLabel.visible = true;
				}
			}
			
			else
			{
				sendReviewData();
				
				trace(nameTextInput.text);
				trace(ratingTxtComp.textArea.text);
				trace(ratingComp.currentSelectedIndex);
			}
		}
		
		private function onNameTextFocus():void
		{
			scroller.scrollToPosition(0,nameTextInput.y,0);
			nameErrorLabel.visible = false;
		}
		
		private function onCommentTextFocus():void
		{
			this.addEventListener(FeathersEventType.SOFT_KEYBOARD_DEACTIVATE, onSoftKeyBoardDeactivate);
			scroller.scrollToPosition(0,ratingTxtComp.y,0);
			isKeyBoardActiveForTextArea = true;
			commentsErrorLabel.visible = false;
			this.invalidate(INVALIDATION_FLAG_SIZE);
		}
		
		private function sendReviewData():void
		{
			var nameCityTextArr:Array = new Array("","");
			nameCityTextArr = nameTextInput.text.split('-');
			
			if(nameCityTextArr.length == 1)
			{
				nameCityTextArr[1] = "";
			}
			
			
			var url:String = "http://speiusscare.co.uk/sitterApp/api.php?mod=users&method=postEmployeeReviews&reviewer_id=" +FetchRemoteData.choosenEmployeeData.id+ 
				"&rate_num=" +ratingComp.currentSelectedIndex+ "&review_desc=" +ratingTxtComp.textArea.text+ "&cname=" +nameCityTextArr[0]+ "&ctitle=" +nameCityTextArr[1];
			var request:URLRequest=new URLRequest();
			request.url = url;
			request.method = URLRequestMethod.GET;
			
			var loader:URLLoader = new URLLoader();
			loader.addEventListener(flash.events.Event.COMPLETE, onJobSuccessfullPosted);
			loader.addEventListener(IOErrorEvent.IO_ERROR, onError);
			loader.load(request);
		}
		
		protected function onJobSuccessfullPosted(event:flash.events.Event):void
		{
			var alertObject:Object = new Object();
			alertObject.message = "Your Review was successfully Posted.";
			alertObject.title = "Speiuss";
			alertObject.buttons = Vector.<String>(["OK"]);
			ShowNativeAlert.showAlertAndGetResponse(alertObject, okButtonTriggeredHandler);
		}
		
		protected function okButtonTriggeredHandler(event:NativeDialogEvent):void
		{
			FetchRemoteData.getClient().populateReviewData();
			this.dispatchEventWith(TRIGGER_CUSTOMER_REVIEW, false, "customerReview");
		}
		
		protected function onError(event:IOErrorEvent):void
		{
			var alertObject:Object = new Object();
			alertObject.message = "Cannot able process your request. \nPlease check your internet connection!";
			alertObject.title = "Speiuss";
			alertObject.buttons = Vector.<String>(["OK"]);
			ShowNativeAlert.showAlert(alertObject);
		}
		
		
		private function onSoftKeyBoardDeactivate():void
		{
			this.removeEventListener(FeathersEventType.SOFT_KEYBOARD_DEACTIVATE, onSoftKeyBoardDeactivate);
			isKeyBoardActiveForTextArea = false;
			this.invalidate(INVALIDATION_FLAG_SIZE);
			nameTextInput.setFocus();
		}
	}
}